package cn.felord.dmn.http;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.drools.util.IoUtils;
import org.kie.api.builder.Message;
import org.kie.dmn.api.core.DMNDecisionResult;
import org.kie.dmn.api.core.DMNResult;
import org.kie.dmn.feel.codegen.feel11.CodegenStringUtil;
import org.kie.dmn.feel.lang.types.impl.ComparablePeriod;
import org.kie.kogito.Application;
import org.kie.kogito.decision.DecisionExecutionIdUtils;
import org.kie.kogito.decision.DecisionModel;
import org.kie.kogito.decision.DecisionModels;
import org.kie.kogito.dmn.rest.DMNFEELComparablePeriodSerializer;
import org.kie.kogito.dmn.rest.DMNJSONUtils;
import org.kie.kogito.dmn.rest.KogitoDMNResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/User Score"})
public class User_32ScoreResource {
    @Autowired
    Application application;
    private static final String KOGITO_DECISION_INFOWARN_HEADER = "X-Kogito-decision-messages";
    private static final String KOGITO_EXECUTION_ID_HEADER = "X-Kogito-execution-id";
    private static final ObjectMapper objectMapper;

    public User_32ScoreResource() {
    }

    @PostMapping(
            value = {""},
            produces = {"application/json"},
            consumes = {"application/json"}
    )
    @RequestBody(
            content = {@Content(
                    mediaType = "application/json",
                    schema = @Schema(
                            ref = "/dmnDefinitions.json#/definitions/InputSetUser_32Score"
                    )
            )},
            description = "DMN input"
    )
    @ApiResponse(
            content = {@Content(
                    mediaType = "application/json",
                    schema = @Schema(
                            ref = "/dmnDefinitions.json#/definitions/OutputSetUser_32Score"
                    )
            )},
            description = "DMN output"
    )
    public ResponseEntity<?> dmn(@org.springframework.web.bind.annotation.RequestBody(required = false) Map<String, Object> variables) {
        DecisionModel decision = ((DecisionModels)this.application.get(DecisionModels.class)).getDecisionModel("https://kiegroup.org/dmn/_35671C72-1E3E-4606-9B92-DE617A45C2D1", "User Score");
        DMNResult decisionResult = decision.evaluateAll(DMNJSONUtils.ctx(decision, variables));
        KogitoDMNResult result = new KogitoDMNResult("https://kiegroup.org/dmn/_35671C72-1E3E-4606-9B92-DE617A45C2D1", "User Score", decisionResult);
        return this.enrichResponseHeaders(decisionResult, this.extractContextIfSucceded(result));
    }

    @GetMapping(
            produces = {"application/xml"}
    )
    public String dmn() throws IOException {
        return new String(IoUtils.readBytesFromInputStream(this.getClass().getResourceAsStream(CodegenStringUtil.escapeIdentifier("User Score") + ".dmn_nologic")));
    }

    private Map.Entry<HttpStatus, ?> buildFailedEvaluationResponse(KogitoDMNResult result) {
        return new AbstractMap.SimpleEntry(HttpStatus.INTERNAL_SERVER_ERROR, result);
    }

    private Map.Entry<HttpStatus, ?> extractContextIfSucceded(KogitoDMNResult result) {
        return (Map.Entry)(!result.hasErrors() ? new AbstractMap.SimpleEntry(HttpStatus.OK, this.buildResponse(result.getDmnContext())) : this.buildFailedEvaluationResponse(result));
    }

    private Map.Entry<HttpStatus, ?> extractSingletonDSIfSucceded(KogitoDMNResult result) {
        return (Map.Entry)(!result.hasErrors() ? new AbstractMap.SimpleEntry(HttpStatus.OK, this.buildResponse(((DMNDecisionResult)result.getDecisionResults().get(0)).getResult())) : this.buildFailedEvaluationResponse(result));
    }

    private ResponseEntity buildDMNResultResponse(KogitoDMNResult result) {
        if (!result.hasErrors()) {
            return ResponseEntity.ok(this.buildResponse(result));
        } else {
            Map.Entry<HttpStatus, ?> response = this.buildFailedEvaluationResponse(result);
            return ResponseEntity.status((HttpStatus)response.getKey()).body(response.getValue());
        }
    }

    private String buildResponse(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException var3) {
            throw new RuntimeException(var3);
        }
    }

    private ResponseEntity enrichResponseHeaders(DMNResult result, Map.Entry<HttpStatus, ?> response) {
        ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.status((HttpStatus)response.getKey());
        if (!result.getMessages().isEmpty()) {
            String infoWarns = (String)result.getMessages().stream().map((m) -> {
                Message.Level var10000 = m.getLevel();
                return "" + var10000 + " " + m.getMessage();
            }).collect(Collectors.joining(", "));
            bodyBuilder.header("X-Kogito-decision-messages", new String[]{infoWarns});
        }

        DecisionExecutionIdUtils.getOptional(result.getContext()).ifPresent((executionId) -> {
            bodyBuilder.header("X-Kogito-execution-id", new String[]{executionId});
        });
        return bodyBuilder.body(response.getValue());
    }

    @PostMapping(
            value = {"dmnresult"},
            produces = {"application/json"},
            consumes = {"application/json"}
    )
    @RequestBody(
            content = {@Content(
                    mediaType = "application/json",
                    schema = @Schema(
                            ref = "/dmnDefinitions.json#/definitions/InputSetUser_32Score"
                    )
            )},
            description = "DMN input"
    )
    public ResponseEntity<?> dmn_dmnresult(@org.springframework.web.bind.annotation.RequestBody(required = false) Map<String, Object> variables) {
        DecisionModel decision = ((DecisionModels)this.application.get(DecisionModels.class)).getDecisionModel("https://kiegroup.org/dmn/_35671C72-1E3E-4606-9B92-DE617A45C2D1", "User Score");
        DMNResult decisionResult = decision.evaluateAll(DMNJSONUtils.ctx(decision, variables));
        KogitoDMNResult result = new KogitoDMNResult("https://kiegroup.org/dmn/_35671C72-1E3E-4606-9B92-DE617A45C2D1", "User Score", decisionResult);
        return this.buildDMNResultResponse(result);
    }

    static {
        objectMapper = (new ObjectMapper()).registerModule(new JavaTimeModule()).registerModule((new SimpleModule()).addSerializer(ComparablePeriod.class, new DMNFEELComparablePeriodSerializer())).disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).disable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS);
    }
}
